package notification

import (
	"fmt"
	"sync"
	"time"

	"health-check/internal/config"
	"health-check/internal/logger"
)

// NotificationRecord 通知记录
type NotificationRecord struct {
	MessageType MessageType `json:"message_type"`
	ServerID    string      `json:"server_id"`
	ProcessName string      `json:"process_name"`
	LastSent    time.Time   `json:"last_sent"`
	Count       int         `json:"count"`
	FirstSent   time.Time   `json:"first_sent"`
}

// SmartNotifier 智能通知器
type SmartNotifier struct {
	mu         sync.RWMutex
	rules      map[MessageType]*config.NotificationRule
	records    map[string]*NotificationRecord
	aggregator *MessageAggregator
}

// NewSmartNotifier 创建智能通知器
func NewSmartNotifier(feishuConfig config.FeishuConfig) *SmartNotifier {
	sn := &SmartNotifier{
		rules:      make(map[MessageType]*config.NotificationRule),
		records:    make(map[string]*NotificationRecord),
		aggregator: NewMessageAggregator(5*time.Minute, 10), // 5分钟内聚合，最多10条消息
	}

	// 设置规则（从配置文件或默认值）
	sn.setRules(feishuConfig.Rules)

	// 启动清理协程
	go sn.cleanup()

	return sn
}

// setRules 设置通知规则
func (sn *SmartNotifier) setRules(configRules map[string]config.NotificationRule) {
	// 默认规则
	defaultRules := map[MessageType]*config.NotificationRule{
		MessageTypeProcessAlert: {
			MessageType:    "process_alert",
			MinInterval:    30 * time.Second,
			MaxFrequency:   20,
			QuietHours:     []config.TimeRange{{Start: "22:00", End: "08:00"}},
			EscalationTime: 5 * time.Minute,
			Enabled:        true,
		},
		MessageTypeProcessRestart: {
			MessageType:    "process_restart",
			MinInterval:    1 * time.Minute,
			MaxFrequency:   20,
			QuietHours:     []config.TimeRange{{Start: "22:00", End: "08:00"}},
			EscalationTime: 5 * time.Minute,
			Enabled:        true,
		},
		MessageTypeProcessRecovery: {
			MessageType:    "process_recovery",
			MinInterval:    30 * time.Second,
			MaxFrequency:   30,
			QuietHours:     []config.TimeRange{},
			EscalationTime: 0,
			Enabled:        true,
		},
		MessageTypeSystemAlert: {
			MessageType:    "system_alert",
			MinInterval:    5 * time.Minute,
			MaxFrequency:   5,
			QuietHours:     []config.TimeRange{{Start: "22:00", End: "08:00"}},
			EscalationTime: 15 * time.Minute,
			Enabled:        true,
		},
		MessageTypeTest: {
			MessageType:    "test",
			MinInterval:    1 * time.Minute,
			MaxFrequency:   60,
			QuietHours:     []config.TimeRange{},
			EscalationTime: 0,
			Enabled:        true,
		},
	}

	// 如果配置文件中有规则，则使用配置文件中的规则覆盖默认规则
	if configRules != nil {
		for msgTypeStr, configRule := range configRules {
			var msgType MessageType
			switch msgTypeStr {
			case "process_alert":
				msgType = MessageTypeProcessAlert
			case "process_restart":
				msgType = MessageTypeProcessRestart
			case "process_recovery":
				msgType = MessageTypeProcessRecovery
			case "system_alert":
				msgType = MessageTypeSystemAlert
			case "test":
				msgType = MessageTypeTest
			default:
				logger.Warnf("未知的消息类型: %s", msgTypeStr)
				continue
			}

			// 使用配置文件中的规则
			sn.rules[msgType] = &configRule
		}
	} else {
		// 使用默认规则
		for msgType, rule := range defaultRules {
			sn.rules[msgType] = rule
		}
	}
}

// SetRule 设置通知规则
func (sn *SmartNotifier) SetRule(msgType MessageType, rule *config.NotificationRule) {
	sn.mu.Lock()
	defer sn.mu.Unlock()
	sn.rules[msgType] = rule
}

// GetRule 获取通知规则
func (sn *SmartNotifier) GetRule(msgType MessageType) *config.NotificationRule {
	sn.mu.RLock()
	defer sn.mu.RUnlock()
	return sn.rules[msgType]
}

// ShouldNotify 判断是否应该发送通知
func (sn *SmartNotifier) ShouldNotify(msgType MessageType, serverID, processName string) bool {
	sn.mu.Lock()
	defer sn.mu.Unlock()

	rule, exists := sn.rules[msgType]
	if !exists || !rule.Enabled {
		return false
	}

	// 检查静默时间
	if sn.isInQuietHours(rule) {
		return false
	}

	key := sn.getKey(msgType, serverID, processName)
	record, exists := sn.records[key]
	now := time.Now()

	if !exists {
		// 首次通知
		sn.records[key] = &NotificationRecord{
			MessageType: msgType,
			ServerID:    serverID,
			ProcessName: processName,
			LastSent:    now,
			Count:       1,
			FirstSent:   now,
		}
		return true
	}

	// 检查最小间隔
	if now.Sub(record.LastSent) < rule.MinInterval {
		logger.Debugf("智能通知过滤: %s 距离上次发送时间 %v < 最小间隔 %v", msgType, now.Sub(record.LastSent), rule.MinInterval)
		return false
	}

	// 检查频率限制
	if sn.isFrequencyExceeded(record, rule) {
		return false
	}

	// 检查升级时间
	if rule.EscalationTime > 0 && now.Sub(record.FirstSent) > rule.EscalationTime {
		// 升级通知，重置计数
		record.Count = 1
		record.FirstSent = now
		record.LastSent = now
		return true
	}

	// 更新记录
	record.Count++
	record.LastSent = now

	return true
}

// isInQuietHours 检查是否在静默时间
func (sn *SmartNotifier) isInQuietHours(rule *config.NotificationRule) bool {
	if len(rule.QuietHours) == 0 {
		return false
	}

	now := time.Now()
	currentTime := now.Format("15:04")

	for _, quietHour := range rule.QuietHours {
		if sn.isTimeInRange(currentTime, quietHour.Start, quietHour.End) {
			return true
		}
	}

	return false
}

// isTimeInRange 检查时间是否在范围内
func (sn *SmartNotifier) isTimeInRange(current, start, end string) bool {
	// 简单的时间比较，支持跨天
	if start <= end {
		return current >= start && current <= end
	} else {
		// 跨天情况
		return current >= start || current <= end
	}
}

// isFrequencyExceeded 检查是否超过频率限制
func (sn *SmartNotifier) isFrequencyExceeded(record *NotificationRecord, rule *config.NotificationRule) bool {
	now := time.Now()
	hourAgo := now.Add(-time.Hour)

	// 如果首次发送时间在1小时内，检查计数
	if record.FirstSent.After(hourAgo) {
		return record.Count > rule.MaxFrequency
	}

	// 如果首次发送时间超过1小时，重置计数
	record.Count = 1
	record.FirstSent = now
	return false
}

// getKey 生成记录键
func (sn *SmartNotifier) getKey(msgType MessageType, serverID, processName string) string {
	return fmt.Sprintf("%s:%s:%s", msgType, serverID, processName)
}

// cleanup 清理过期记录
func (sn *SmartNotifier) cleanup() {
	ticker := time.NewTicker(1 * time.Hour)
	defer ticker.Stop()

	for range ticker.C {
		sn.mu.Lock()
		now := time.Now()

		for key, record := range sn.records {
			// 清理超过24小时的记录
			if now.Sub(record.FirstSent) > 24*time.Hour {
				delete(sn.records, key)
			}
		}

		sn.mu.Unlock()
	}
}

// GetAggregatedMessage 获取聚合消息
func (sn *SmartNotifier) GetAggregatedMessage(msgType MessageType, serverID, processName string) *AggregatedMessage {
	return sn.aggregator.GetMessage(msgType, serverID, processName)
}

// AddMessage 添加消息到聚合器
func (sn *SmartNotifier) AddMessage(msgType MessageType, serverID, processName, message, status string) *AggregatedMessage {
	return sn.aggregator.AddMessage(msgType, serverID, processName, message, status)
}

// GetStats 获取统计信息
func (sn *SmartNotifier) GetStats() map[string]interface{} {
	sn.mu.RLock()
	defer sn.mu.RUnlock()

	stats := make(map[string]interface{})
	stats["total_records"] = len(sn.records)
	stats["total_rules"] = len(sn.rules)

	// 按类型统计
	typeStats := make(map[MessageType]int)
	for _, record := range sn.records {
		typeStats[record.MessageType]++
	}
	stats["type_stats"] = typeStats

	return stats
}
